<script setup>
import {useRoute,useRouter} from "vue-router";
import CatalogService from "../../stores/CatalogService";

const products = ref([
  {
    productId: '',
    categoryId: '',
    name: '',
    description:''
  }
]);
const route = useRoute();
const router = useRouter();
const categoryId = route.params.categoryId

const getProducts = async (cid)=>{
  const [err, res] = await CatalogService.promise_process(CatalogService.getProducts(cid))
  if(err){
    console.log(err)
    ElMessage({
      message: '请求服务器失败',
      type: 'error',
    })
  }
  if(res){
    //console.log(products)
    products.value = res.data;
  }
}

const toItem =  (cid,pid)=>{
  router.push({
    name:"item",
    params: {
      categoryId:cid ,
      productId :pid
    }
  })
}

const bindBase64 = (base64Code) =>{
  return "data:image/png;base64," + base64Code
}

watch(categoryId, (newCid, oldCid) =>{
  console.log("newCid:",newCid)
  console.log("oldCid:", oldCid)
  getProducts(newCid)
})

onMounted( ()=>{
  getProducts(categoryId)
})

</script>

<template>
    <top />
  <div id="Main">
    <div id="BackLink">
      <router-link to="/catalog/category">Return to Categories</router-link>
    </div>
    <div id="Catalog">

      <h2 id="productId" style="text-align: center ;padding-top: 80px">{{ categoryId }}</h2>

      <el-card>
        <el-table :data="products" style="width: 100%">
          <el-table-column prop="productId" label="Product ID" align="center">

            <template v-slot="scope">
              <div class="el-button" style="color: deepskyblue" @click="toItem(categoryId,scope.row.productId)">
                {{ scope.row.productId }}
              </div>
            </template>

          </el-table-column>
          <el-table-column prop="name" label="Name" align="center"></el-table-column>
          <el-table-column label="Photo">
            <template v-slot="scope">
              <img :src="bindBase64(scope.row.description)" />
            </template>
          </el-table-column>
        </el-table>
      </el-card>

    </div>
  </div>

    <bottom />
</template>

<style scoped>
#Main{
  /*border: solid red;*/
  padding: 10px;
  width: 80vw;
  height: 75vh;
}
#BackLink{
  position: relative;
  border-top: solid blue;
  border-bottom: solid blue;
  width: 20%;
  height: 50px;
  float: right;
  /*以下3个令文字处于div块正中央，webkit兼容Chrome*/
  display: -webkit-box;
  -webkit-box-align: center;
  -webkit-box-pack: center;
}
el-table{
  position:relative;
  float: bottom;
  border: solid red;
  bottom: 10%;
  margin-top: 1000px;
}
</style>
